<?php

namespace App\Http\Controllers\Dashboard;

use App\Models\Menu;
use App\Models\Org;
use App\Models\OrgMenu;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;


class MenuController extends BaseController
{
    /**
     * 获取当前登录机构的菜单
     * @param Request $request
     * @return JsonResponse
     */
    public  function tree(Request $request) {
        $user = $request->user();

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => [
                'menu' => $user->isSupper() ?
                    build_tree(Menu::all()->makeHidden(['created_at','updated_at'])) : build_tree(getOrgMenu($user->org_code))
            ]
        ]);
    }

    /**
     * 指定机构的菜单
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function ids(Request $request, $id) {
        $org = Org::ofOrgCode($request->user())->find($id);
        if (empty($org)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => []
            ]);
        }

        return response()->json([
            'code' => 0,
            'msg' => 'ok',
            'data' => OrgMenu::where('org_id', $id)->pluck('menu_id')->toArray()
        ]);
    }

    /**
     * 保存菜单
     *
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function  saveIds(Request $request, $id) {
        $org = Org::ofOrgCode($request->user())->find($id);
        if (empty($org)) {
            return response()->json([
                'code' => 1,
                'msg' => '没有数据权限',
                'data' => []
            ]);
        }

        $org->menus()->sync($request->ids);
        return response()->json([
            'code' => 0,
            'msg' => '保存成功',
            'data' => []
        ]);
    }
}
